package cn.wzvtc.miniserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * 请求转发处理
 * @author Shiwei Xu
 * @date 2020/3/3
 */
public class Dispatcher implements HttpHandler {

  private UserController userController;
  private ObjectMapper objectMapper;

  public Dispatcher(UserController userController) {
    this.userController = userController;
    this.objectMapper = new ObjectMapper();
  }

  @Override
  public void handle(HttpExchange exchange) throws IOException {
    String requestPath = exchange.getRequestURI().getPath();
    String requestMethod = exchange.getRequestMethod();
    String requestParam = getRequestParam(exchange);
    System.out.printf("当前请求：%s %s\n", requestMethod, requestPath);
    System.out.printf("请求参数：%s\n", requestParam);

    Object result;
    // 根据URL，转发给对应的Controller处理
    switch (requestPath) {
      case "/sys/user/list":
        result = userController.list(); break;
      case "/sys/user/add":
        User userToAdd = objectMapper.readValue(requestParam, User.class);
        result = userController.add(userToAdd);
        break;
      default:
        result = null;
        break;
    }
    // 输出处理完得到的结果
    writeResponse(exchange, result);
  }

  /**
   * 读取前端的请求参数
   * 支持GET与POST
   */
  private String getRequestParam(HttpExchange exchange) throws IOException {
    String paramStr = "";

    if (exchange.getRequestMethod().equals("GET")) {
      // GET请求读queryString
      paramStr = exchange.getRequestURI().getQuery();
    } else {
      // 非GET请求读请求体
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), "utf-8"));
      StringBuilder requestBodyContent = new StringBuilder();
      String line = null;
      while ((line = bufferedReader.readLine()) != null) {
        requestBodyContent.append(line);
      }
      paramStr = requestBodyContent.toString();
    }

    return paramStr;
  }

  /**
   * 返回数据给前端
   */
  private void writeResponse(HttpExchange exchange, Object result) throws IOException {
    // 生成响应体
    byte[] responseContentByte = objectMapper.writeValueAsBytes(result);

    // 设置响应头，必须在sendResponseHeaders方法之前设置！
    exchange.getResponseHeaders().add("Content-Type:", "json;charset=utf-8");
    // 设置响应码和响应体长度，必须在getResponseBody方法之前调用！
    exchange.sendResponseHeaders(200, responseContentByte.length);
    // 输出
    OutputStream out = exchange.getResponseBody();
    out.write(responseContentByte);
    out.flush();
    out.close();
  }
}
